from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from utils.token import check_token

# 需要登录才能访问的接口
LOGIN_REQUIRED_URLS = {
    '/users/getUserMsg',
    '/system/menu/getMenu',
    '/system/menu/addMenu',
    '/system/menu/delMenu',
    '/system/menu/upMenu',
    '/system/menu/getMenuSelect',
    '/system/menu/getMenuTemplate',
    '/system/menu/addMenuTemplate',
    '/system/menu/delMenuTemplate',
    '/system/menu/upMenuTemplate',
}
# 需要1级权限的接口
PERMISSION_1 = {
    '/system/menu/getMenu',
    '/system/menu/addMenu',
    '/system/menu/delMenu',
    '/system/menu/upMenu',
    '/system/menu/getMenuSelect',
    '/system/menu/getMenuTemplate',
    '/system/menu/addMenuTemplate',
    '/system/menu/delMenuTemplate',
    '/system/menu/upMenuTemplate',
}


class CheckLogin(MiddlewareMixin):

    def process_request(self, request):
        # 请求的资源路径在上面的集合中
        if request.path in LOGIN_REQUIRED_URLS:
            token = request.session.get("token")
            if token is not None:
                data = check_token(token)
                if not (data is not None and data.get('user_id') and data.get('ip') and data.get('permission')):
                    # 刷新session缓存
                    request.session.flush()
                    return JsonResponse({"state": 300, "message": "登录过期", "data": {}}, safe=False)
                else:
                    permission = data["permission"]
                    if permission > 1 and request.path in PERMISSION_1:
                        return JsonResponse({"state": 600, "message": "权限不足", "data": {}}, safe=False)
            else:
                # 刷新session缓存
                request.session.flush()
                return JsonResponse({"state": 300, "message": "未登录", "data": {}}, safe=False)

    def process_exception(self, request, exception):
        print('CheckLogin error')
        return JsonResponse({"state": 500, "message": "服务器错误", "data": str(exception)}, safe=False)

    def process_response(self, request, response):
        return response
